<?php
namespace app\index\controller;

use app\model\Members;
use app\model\Util;
use MoCommon\Business\BizCodes;
use MoCommon\DataState\PicLogStatus;
use MoCommon\DataState\QuestionLogType;
use MoCommon\DataState\TradeLogPayIssueStatus;
use MoCommon\DataState\TradeLogStatus;
use MoCommon\DataState\TradeLogType;
use MoCommon\Support\Codes;
use MoCommon\Support\Helper;
use MoCommon\WeChat\Wx;
use OSS\OssClient;
use think\Db;
use think\facade\Cache;
use think\facade\Config;
use app\index\Thirdparty\WxpayCoreTrait;

class Index extends Apibase
{
    private static $memberModel;
    public function __construct()
    {
        self::$memberModel=new Members();
    }

    use WxpayCoreTrait;
    /**
     * 问诊首页列表数据
     * @return \think\response\Json
     */
    public function doclist()
    {
        $page=input('page',1);
        //验签
        parent::sign_validate();
        $limit_condition = ['limit' => 50,'page'=>$page];
        $cond = "answer_role_id <> 0 AND answer_role_id IN (select id from appname_m_members where isrenzheng>0)";
        // 统计最多回复数倒序
        $data = self::$memberModel->answerStatistic($limit_condition, $cond);
        // 用户 id, name, headimg, hospital, describe
        $role_ids = array_column($data, 'answer_role_id');
        $members = self::$memberModel->necessInfoByWhere(Helper::join_condition($role_ids, 'id'), true);
        // 被采纳数
//        $adopt = self::$memberModel->adoptCount($role_ids);

        // 当前用户是否已关注
//        $collects = self::$memberModel->findUserCollect($role_ids, $user_id, true);
        if ($data) {
            foreach ($data as $k => &$v) {
                if ($v['answer_role_id'] && isset($members[$v['answer_role_id']])) {
                    $v['name'] = $members[$v['answer_role_id']]['name'];
                    $v['authen'] = $members[$v['answer_role_id']]['isrenzheng'];
                    $v['headimg'] = $members[$v['answer_role_id']]['headimg'];
                    $v['hospital'] = $members[$v['answer_role_id']]['hospital'];
                    $v['describe'] = $members[$v['answer_role_id']]['description'];
                    $v['zhicheng'] = $members[$v['answer_role_id']]['zhicheng'];
                    $v['depname'] = $members[$v['answer_role_id']]['administrative'];
//                    $v['adopt_count'] = isset($adopt[$v['answer_role_id']]['adopt_count']) ?
//                        $adopt[$v['answer_role_id']]['adopt_count'] : 0;
//                    $v['is_follow'] = (isset($collects[$v['answer_role_id']]['status'])
//                        && ($collects[$v['answer_role_id']]['status'] == CollectLogStatus::YES)) ?
//                        $collects[$v['answer_role_id']]['status'] : 0;
                    $v['question_price'] = $members[$v['answer_role_id']]['question_price'];
//                    $v['question_kprice'] = $members[$v['answer_role_id']]['question_kprice'];
                } else {
                    // id = 0 等无用数据
                    unset($data[$k]);
                }
            }
        }
        return parent::respond($data);
    }

    /**
     * 用户提问保存
     */
    public function ask()
    {
        //验签
        parent::sign_validate();
        $data = [];
        $role_id = parent::getUid();
        $question = input('question');
        $description = input('description');
        if (empty($question) || empty($description)) {
            $status = Codes::PARAM_ERR;
            $msg = "问题或描述不能为空";
            return parent::respond([], $status, $msg);
        }
        // 付费问不公开
        $data['pay_issue_isopen'] = 0;
        // 新增问题
        $data['question'] = $question;
        $data['description'] = $description;
        $data['addtime'] = $data['updatetime'] = $_SERVER['REQUEST_TIME'];
        $data['role_id'] = $role_id;
        $data['k_price'] = 0;
        $data['depid'] = 0;
        $data['type'] = 6;
        $pics = input('pics');
        $full_info = parent::full_info();
        if (empty($full_info['description']) && empty($role_id)) {
            // 必须关注公众号
            $status = BizCodes::MUST_SUBSCRIBE;
            $msg = BizCodes::get($status);
            return parent::respond([], $status, $msg);
        }

        $question_id = self::$memberModel->insertAsk($data);
        if ($question_id) {
            // 图片数据
            if ($role_id) {
                $pics = json_decode($pics, true);
            }
            if ($pics) {
                self::$memberModel->insertPics($pics, $role_id, $question_id);
            }

            $count = self::$memberModel->countAsk(['role_id' => $role_id]);
            self::$memberModel->updateMembers(['question_num' => $count], ['id' => $role_id]);
            $status = Codes::ACTION_SUC;
            $max = $question_id + 20000;
            $msg = Codes::get($status) . "!
            您是医库第 $max 个问题的发布者";

        } else {

            $status = Codes::INSERT_ERR;
            $msg = Codes::get($status);
        }
        return parent::respond([], $status, $msg);
    }

    /**
     * 用户提问上传图片
     */
    public function uploadfiles()
    {
        //验签
        parent::sign_validate();
        $wechat = Config::get('app.wechat');
        $appid = $wechat['appid'];
        $secret = $wechat['secret'];
        Wx::init([$appid, $secret]);
        // 获取基础 access_token
        $access_token = Util::get_access_token();
        $media_id = input('media_id');
        //根据media_id ,微信服务器请求获取上传文件
        $media = Wx::media_get($access_token, $media_id);

        //获取头信息
        $ext_type = $media["header"]["content_type"];
        $ext_ary = explode('/', $ext_type);

        //异常处理,针对access_token被篡改后重新请求
        if ($ext_ary[0] != 'image') {
            $this->logger->log("upload error result:" . json_encode($media));
            // 更新基础 access_token
            $access_token = Util::update_access_token();
            $media = Wx::media_get($access_token, $media_id);

            //获取头信息
            $ext_type = $media["header"]["content_type"];
            $ext_ary = explode('/', $ext_type);
        }

        //上传到阿里云
        $suffix = '.' . $ext_ary[count($ext_ary) - 1];
        // 文件名称
        $object_name = static::correctFilename('', $suffix);

        $alioss = Config::get('app.alioss');
        $accessKeyId = $alioss['accesskey'];
        $accessKeySecret = $alioss['accesskeysecret'];
        $endpoint = $alioss['endpoint'];
        // 存储空间名称
        $bucket = $alioss['bucket'];

        try {
            $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);
            $ossClient->uploadFile($bucket, $object_name, $media['body']);
        } catch (OssException $e) {
            //文件上传失败
        }
        return parent::respond($object_name);
    }

    //我的咨询
    public function mypayissue()
    {
        //验签
        parent::sign_validate();
        $st = input('status', 0);//0未完成;1已完成
        $user_id = parent::getUid();

        $str = "type = '" . TradeLogType::ONE_TO_ONE . "' AND uid = '{$user_id}'";

        if($st==0){
            $st="1";//1未完成;
        }else{
            $st="0,2,3";//(0,2,3)已完成
        }
        if ($st) {
            $arr = explode(',', $st);
            foreach ($arr as &$v) {
                $v = (int)$v;
            }
            $str .= " AND pay_issue_status IN(" . implode(',', $arr) . ")";
        }

        $orders = self::$memberModel->tradeClomn($str, 'id, question_id,to_uid, pay_issue_status, status AS pay_status');
        $question_ids = array_unique(array_column($orders, 'question_id'));
//        $orders = self::$memberModel->attachMember($orders, 'to_uid', 'doctor_info');

        $questions = $this->got([
            'conditions' => Helper::join_condition($question_ids, 'question_id'),
        ], true);
        $questions = Helper::array_column_combine($questions, 'question_id');
        foreach ($orders as &$value) {
            $value['question_detail'] = $questions[$value['question_id']] ?: [];
//            $value['reply_hint_num'] = GeneralMessage::newSinglePayQuestionReplyAct($user_id,$value['question_id'],'get');
//            $value['other_is_reply'] = GeneralMessage::SinglePayQuestionOtherIsReplyAct($user_id,$value['question_id']);
        }

        return parent::respond($orders);
    }

    //注册用户接口
    public function login()
    {
        //验签
        parent::sign_validate();
        $openid = input('openid', 0);//微信openid
        $name = input('name', '');//微信昵称
        $headimg = input('headimg', '');//微信头像
        $data = array(
            "openid" => $openid,
            "name" => $name,
            "headimg" => $headimg
        );
        //查询当前用户是否已经注册
        $isdata = Db::table('appname_m_members')
            ->where('openid', $openid)
            ->find();
        if ($isdata) {
            if ($isdata['name'] != $name || $isdata['headimg'] != $headimg) {
                //更新昵称和头像
                Db::table('appname_m_members')
                    ->where('openid', $openid)
                    ->where('id', $isdata['id'])
                    ->update($data);
                $isdata['name'] = $name;
                $isdata['headimg'] = $headimg;
            }
            //当前用户已经注册过了
            $userid = $isdata['id'];
            $data['id'] = $userid;
        } else {
            $userid = Db::table('appname_m_members')
                ->insertGetId($data);
            $data['id'] = $userid;
        }

        // 给用户生成token
        $sign = Helper::gentoken($userid);
        //存入redis
        $options = Config::get('app.converse');
        $redis = Cache::init($options);
        $redis->set($sign, json_encode($data), $options['expire']);
        $return_data = array(
            "user_sign" => $sign,
            "user_info" => $data
        );
        return parent::respond($return_data);
    }

    //问题详情
    public  function detail($id)
    {
        //验签
        parent::sign_validate();
        $question_id=$id;
        $where['conditions'] = "question_id = {$question_id}";

//        if (! $data = WendaLogCache::getBody($question_id) ) {

            // 问题详情
            $data = $this->got($where, false);


            //删除的帖子处理
            if ( isset($data[0]['is_del']) && ($data[0]['is_del']==1) ) {

                $status = Codes::ACTION_FAL;
                $msg = Codes::get($status);
                return parent::respond(null,$status,$msg);
            }

            $data = reset($data);
            $w = "question_id = {$data['question_id']} AND uid = {$data['role_id']} AND type = " . TradeLogType::ONE_TO_ONE;

            // 付费问
            if ( $data['type'] ==QuestionLogType::PAYMENT ) {

                // 未公开
                $t = self::$memberModel->tradeClomn($w, 'id, question_id,to_uid, pay_issue_status');
//
//                if ( ( $data['pay_issue_isopen'] == QuestionLogPayIssueIsopen::NOT )
//                    && ( $data['role_id'] != $role_id )
//                    && ($t && ! in_array($role_id,  array_unique(array_column($t, 'to_uid'))) )
//                ) {
//                    $status = BizCodes::PAY_ISSUE_NOT_OPEN;
//                    $msg = BizCodes::get($status);
//                    return parent::respond(null,$status,$msg);
//                } else {
                    // 评分
                    $score=Db::table('appname_zhaoyisheng_trade_log')
                        ->field('trade_score')
                        ->where($w)
                        ->find();
                    $data['trade_score']=sprintf('%.1f',$score['trade_score']);
                    $data['trade'] = $t[0];
//                }
            }


//            WendaLogCache::setBody($question_id, json_encode($data));
//        }

        // 回复列表
        $replys = self::$memberModel->replys($where, 0);

        $data['replys'] = $replys;

//        fastcgi_finish_request();

        // 浏览量 + 1
        self::$memberModel->increaseShownum($question_id);
        //清除付费问答未查看的回复数
//        GeneralMessage::newSinglePayQuestionReplyAct($role_id,$question_id,'delete');
//        // 如果是本人查看, 清空未查看回答数/未查看回复数
//        QuestionLog::clearHintnum($question_id, $role_id);
//        WendaLog::clearHintnum($question_id, $role_id);
        return parent::respond($data);
    }


    //问题回复
    public function reply()
    {
        //验签
        parent::sign_validate();
        $user_id = $this->getUid();
        $return_data = [];
        $question_id = input('question_id');
        $content = input('content');
        $answer_id = input('answer_id', 0);
        $is_anonymous = input('is_anonymous', 0);
        // New
        $trade_id = input('trade_id');
        if (empty($question_id) || empty($content)) {
            $status = Codes::PARAM_ERR;
            $msg = "问题id或者内容不能为空";
            return parent::respond([], $status, $msg);
        }
        $user = self::$memberModel->findMembers(['id' => $user_id], 1);
        $question = self::$memberModel->findQuestion(["question_id" => $question_id]);
        $question_type = $question ? $question['type'] : null;
        $need_kmoney = true;
        if (isset($question_type) && ($question_type == QuestionLogType::NORMAL) && ZQLmodel::hasOvertime($question_id)) {
            $need_kmoney = false;
            // 发布时间超过三天禁止回复
        }

        $pure_content = Helper::pure_content($content);
        $check_repeat = self::$memberModel->findWenda("question_id = $question_id and content like '%$pure_content%' ");
        if ($check_repeat) {
            //不能重复回答问题
            $status = BizCodes::REPLY_REPEAT;
            $msg = BizCodes::get($status);
            return parent::respond([], $status, $msg);
        }

        $website = Config::get('app.website');
        $data = [
            'question_id' => $question_id,
            'content' => $content,

            'parent_id' => $answer_id,
            'answer_role_id' => $user_id,
            'addtime' => $_SERVER['REQUEST_TIME'],
            'is_anonymous' => $is_anonymous,
            'sort' => 0,
            'question_type' => $question_type,
            'type' => 1
        ];

        // 验证
        $validate = parent::badCheck($data['content']);
        if ($validate['status'] != Codes::ACTION_SUC) {
            $status = $validate['status'];
            $msg = $validate['msg'];
            return parent::respond([], $status, $msg);
        }

        // 付费问是否已完成
        if (($question['type'] == QuestionLogType::PAYMENT) && empty($trade_id)) {
            $status = Codes::PARAM_ERR;
            $msg = Codes::get($status);
            return parent::respond([], $status, $msg);
        } else {
            $trade_res = self::$memberModel->findTrade(["id" => $trade_id], "id,question_id,uid, to_uid, pay_issue_status");

            if ($trade_res) {
                // 非求助中都算结束.
                if ($trade_res['pay_issue_status'] != TradeLogPayIssueStatus::ASKING) {
                    $status = BizCodes::PAY_ISSUE_HAS_FINISH;
                    $msg = BizCodes::get($status);
                    return parent::respond([], $status, $msg);
                }

                // 追问限制
                // 患者有两次提问了
                $wencount = self::$memberModel->countWenda("question_id = '{$question_id}' AND answer_role_id = {$user_id} AND answer_role_id = '{$question['role_id']}'");
                if ($wencount >= 2) {
                    $status = BizCodes::QUESTION_ASK_OVER;
                    $msg = BizCodes::get($status);
                    return parent::respond([], $status, $msg);
                }

                //
                $data['type'] = AppnameZhaoyishengWendaLog::TYPE_REPLY_ONE_TO_ONE;

                $wechat = Config::get('app.wechat');
                Wx::init([$wechat['appid'], $wechat['secret']]);
                $access_token = Util::get_access_token();


                $tpl_id = $wechat['onetoone_tpl_id'];

                $shot_content = mb_substr($content, 0, 30);


                // 新回复提醒
                if ($user_id == $trade_res['uid']) {
                    // 提问者，追问

                    //全局提问者提问或者追问消息
//                    GeneralMessage::newPayQuestionMess($trade_res->to_uid);
//                    //新增单个提问未查看次数
//                    GeneralMessage::newSinglePayQuestionReplyAct($trade_res->to_uid,$question_id,'incr');
//
//                    //修改提问回复状态
//
//                    //提问者回复，医生设置成新追问状态
//                    GeneralMessage::SinglePayQuestionOtherIsReplyAct($trade_res->to_uid,$question_id,'incr');
//                    //提问者回复，提问者设置成追问中状态
//                    GeneralMessage::SinglePayQuestionOtherIsReplyAct($trade_res->uid,$question_id,'delete');

                    $time = Helper::format_date(time());
                    $template_data = array(
                        'first' => array('value' => urlencode("您好,咨询者{$user['true_name']}追问:{$shot_content}... "), 'color' => "#743A3A"),
                        'keyword1' => array('value' => urlencode($question['question'])),
                        'keyword2' => array('value' => urlencode($time)),
                        'keyword3' => array('value' => urlencode($question['description'])),
                        'keyword4' => array('value' => urlencode($time)),
                        'remark' => array('value' => urlencode('请尽快回答，详情请点击此处')),
                    );
                    $to_user = self::$memberModel->findMembers("id = {$trade_res['to_uid'] }");
                    $to_openid = $to_user ? $to_user['openid'] : '';

                } else {
                    //全局新付费回答消息
//                    GeneralMessage::newPayQuestionReplyMess($trade_res->uid);
//                    //新增单个提问未查看次数
//                    GeneralMessage::newSinglePayQuestionReplyAct($trade_res->uid,$question_id,'incr');
//
//                    //修改提问回复状态
//
//                    //医生回复，提问者设置成新回复状态。
//                    GeneralMessage::SinglePayQuestionOtherIsReplyAct($trade_res->uid,$question_id,'incr');
//                    //医生回复，医生设置成已回复
//
//                    GeneralMessage::SinglePayQuestionOtherIsReplyAct($trade_res->to_uid,$question_id,'delete');

                    $time = Helper::format_date(time());
                    $template_data = array(
                        'first' => array('value' => urlencode("您好,医生{$user['true_name']}回复:{$shot_content}... "), 'color' => "#743A3A"),
                        'keyword1' => array('value' => urlencode($question['question'])),
                        'keyword2' => array('value' => urlencode($time)),
                        'keyword3' => array('value' => urlencode($question['description'])),
                        'keyword4' => array('value' => urlencode($time)),
                        'remark' => array('value' => urlencode('了解详情请点击此处')),
                    );
                    $to_user = self::$memberModel->findMembers("id = {$trade_res['uid'] }");
                    $to_openid = $to_user ? $to_user['openid'] : '';
                }

                $url = $website['index'] . '#/pay/' . $trade_res['question_id'] . '?status=' . $trade_res['pay_issue_status'] . '&trade_id=' . $trade_res['id'];
                $tpl_ret = Wx::send_template($access_token, $url, $to_openid, $tpl_id, $template_data);
                if ($tpl_ret['errcode'] != 0) {
                    //模板消息发送失败
                }
            }
        }

        if ($answer_id) {
            // 对于回答的回复, 设置路径.
            $_path = self::$memberModel->findWenda(['id' => $answer_id]);
            $_path = $_path['path'];
            if ($_path) $data['path'] = $_path . $answer_id . ',';
        }


        // 新增回答数据
        $new_answer_id = self::$memberModel->reply($data);
        $count = self::$memberModel->countWenda(['answer_role_id' => $user_id]);
        self::$memberModel->updateMembers(['answer_num' => $count], ['id' => $user_id]);


        if ($new_answer_id) {
            if (!$answer_id) {
                // 对问题的回复, 回复数 +1, 未查看数 +1
                self::$memberModel->increaseAnswernum($data['question_id']);
            } else {
                self::$memberModel->increaseHintnum($answer_id);
            }

            // 继续加图片数据

            $pics = input('pics');

            if ($pics && is_array($pics)) {
                foreach ($pics as $v) {
                    $pic_log = [
                        'site' => $v,
                        'role_id' => $data['answer_role_id'],
                        'pic_status' => 1,
                        'addtime' => $data['addtime'],
                        'answer_id' => $new_answer_id,
                    ];
                    Db::table('appname_zhaoyisheng_pic_log')
                        ->insert($pic_log);
                }
            }

            // 付费回答追问限制.
            if (($question['type'] == QuestionLogType::PAYMENT) && (!isset($look_as_simple))) {
                // 患者有两次追问， 医生回答了parent_id=0的两次不同追问，自动结束
                self::$memberModel->checkAutoFinish($question_id, $question['role_id'], $user_id, $trade_id);
            }

//            // clear cache.
//            WendaLogCache::delBody($question_id);
//            WendaLogCache::delReply($question_id);

            $return_data=self::$memberModel->findWenda("id = $new_answer_id","id, is_anonymous,content, parent_id, answer_role_id, dianzannum,question_type,is_open,invite_uid,type, path, sort, FROM_UNIXTIME(addtime, '%m-%d %H:%i') AS create_time, accept_time");

            $pics=Db::table('appname_zhaoyisheng_pic_log')
                ->field('site, content, pic_status, question_id, answer_id, FROM_UNIXTIME(addtime) AS create_time')
                ->where("answer_id = $new_answer_id")
                ->select();
            $new_pics = [];
            if ($pics) {
                foreach ($pics as &$val) {

                    $val['site'] = $website['imgurl'] . $val['site'];
                    $new_pics[] = $val;
                }
                unset($val, $pics);
            }
            $return_data['pic'] = $new_pics;
            $return_data['member_info'] = self::$memberModel->findMembers("id = $user_id",1);

            $status = Codes::ACTION_SUC;


        } else {
            $status = Codes::INSERT_ERR;
        }

        $msg = Codes::get($status);


        if ($status == Codes::ACTION_SUC) {
            $max = $new_answer_id + 1000000;
            $msg = $msg . "!
            您是医库第 $max 个评论的发布者";
        }

        return parent::respond($return_data, $status, $msg);

    }


    //完成之后评分
    public function setscore()
    {
        //验签
        parent::sign_validate();
        $id = input('id');
        $score = input('score');
        $scoremsg = input('scoremsg');
        $role_id = $this->getUid();
        if (!$id || ($score < 1) || ($score > 5)) {
            $status = Codes::PARAM_ERR;
        } else {
            $arr = [
                'id' => $id,
                'uid' => $role_id,
                'status' => TradeLogStatus::HAS_PAID,
                'pay_issue_status' => TradeLogPayIssueStatus::FINISH,
            ];

            $cond = Helper::build_and_condition($arr);
            $tradedata = self::$memberModel->findTrade($cond);
            if (empty($tradedata)) {
                $status = Codes::ACTION_ILL;
            } else {
                $bool = Db::table('appname_zhaoyisheng_trade_log')
                    ->where("id = '{$id}'")
                    ->update([
                        'trade_score' => $score,
                        'pay_issue_status' => TradeLogPayIssueStatus::SCORED,
                        'trade_score_msg' => $scoremsg
                    ]);
                if ($bool) {
                    $status = Codes::ACTION_SUC;
                } else {
                    $status = Codes::ACTION_FAL;
                }
            }
        }
        $msg = Codes::get($status);
        return parent::respond([], $status, $msg);
    }

    //医生详情数据信息
    public function doctor()
    {
        //验签
        parent::sign_validate();
        $member_id = input('member_id');
        //获取医生信息
        $doctor = self::$memberModel->findDoctor("member_id = $member_id AND renzheng = 1");
        //获取患者评价信息
        //评价总数
        $pingjia = Db::table('appname_zhaoyisheng_trade_log')
            ->field('uid,trade_score,trade_score_msg,addtime')
            ->where('type', 4)
            ->where('to_uid', $member_id)
            ->where('pay_issue_status', 3)
            ->select();

        $satisfied = 0;//满意
        $commonly = 0;//一般满意
        $unsatisfy = 0;//不满意

        if ($pingjia) {
            for ($i = 0; $i < count($pingjia); $i++) {
                $mem = self::$memberModel->findMembers(['id' => $pingjia[$i]['uid']], 1);
                $pingjia[$i]['name'] = $mem['name'];
                $pingjia[$i]['headimg'] = $mem['headimg'];
                switch ($pingjia[$i]['trade_score']) {
                    case 1: //不满意
                        $unsatisfy += 1;
                        break;
                    case 2: //一般
                    case 3:
                        $commonly += 1;
                        break;
                    case 4:
                    case 5:
                        $satisfied += 1;
                        break;
                }
            }
        }
        $return = array(
            "doctors" => $doctor,//医生信息
            "all_evaluate" => count($pingjia),//评价总数
            "satisfied_evaluate" => $satisfied,//满意评价总数(4-5)
            "commonly_evaluate" => $commonly,//一般满意总数(2-3)
            "unsatisfy_evaluate" => $unsatisfy,//不满意总数(1),
            "evaluate_list" => $pingjia
        );
        return parent::respond($return);
    }

    /**
     * 数据返回.
     *
     * @param array $where
     * @param bool $short 是否精简数据
     * @param string $user_id 如果是查其他人信息的场合需要
     *
     * @farwish
     */
    protected function got($where = [], $short = false, $user_id = '')
    {
        $page=input('page',1);
        $questions=Db::table('appname_zhaoyisheng_question_log')
            ->where($where['conditions'])
            ->page($page,20)
            ->select();

        if (! $questions) return [];


        // 基于问题: 所有column
        $role_ids = array_column($questions, 'role_id');

        $join_r_ids = join(',', $role_ids) ?: 0;

        // 发表人: id,name,headimg; 5ms

        $members = self::$memberModel->necessInfoByWhere(Helper::join_condition($join_r_ids, 'id'), true);

        // 汇总
        foreach ($questions as $k => &$v) {
            $v['create_time'] = Helper::format_date($v['addtime'], 'm-d H:i');
            unset($v['account_name']);

            $v['m_members'] = isset($members[$v['role_id']]) ? $members[$v['role_id']] : [];

            if (! $short) {
                // 图片列表
                $v['pic_log'] = isset($new_pics[$v['question_id']]) ? $new_pics[$v['question_id']] : [];


                // 补充图片
                $v['pic_exts'] = [];
                if ( isset($pic_exts[$v['question_id']]) ) {
                    foreach ($pic_exts[$v['question_id']] as $key => $list) {
                        if ($key <= PicLogStatus::OPEN) {
                            unset($pic_exts[$v['question_id']][$key]);
                        } else {
                            $v['pic_exts'][] = [
                                'idx' => $key - 1,
                                'create_time' => $list[0]['create_time'],
                                'count' => count($list),
                            ];
                        }
                    }
                }

                // 扩展描述
                $v['question_exts'] = isset($question_exts[$v['question_id']]) ? $question_exts[$v['question_id']] : [];
            }
        }

        return $questions;
    }

    /**
     * 上传和删除时, 返回正确的文件名.
     *
     * debug模式下, 保证文件上传和删除 testing/ 目录内文件.
     *
     * @param string | array $filename 没有时生成文件名; 否则返回正确路径文件名.
     * @param string $suffix 有文件名时不传, 无文件名时传.
     *
     * @return string | array
     *
     * @farwish
     */
    protected static function correctFilename($filename = '', $suffix = '')
    {
        $appconfig = Config::get('app');
        $dir = $appconfig['debug'] ? 'testing/' : '';

        if ($filename) {

            if (is_array($filename)) {
                // 批量模式.
                foreach ($filename as $val) {
                    $name[] = $dir . $val;
                }
            } else {
                // 单一文件.
                $name = $dir . $filename;
            }

        } else {

            // 生成.
            $name = $dir . Helper::custom_mt_uniqid() . $suffix;

        }

        return $name;
    }
}
